 # -*- coding: utf-8 -*-
import sys
import os


  


def loadInstFile(fileName):
  f = open(fileName)
  nucl = []
  while 1:
    line = f.readline()
    if not line:
      break
    nucl.append(line)    
  return nucl

def compNucl(nuclA, nuclB):
  offset = 0
  i = 0
  while(offset<10):
    while(i<10-offset):
      if nuclA[i+offset]==nuclB[i]:
	i+=1
	continue
      else:
	break
     
	
    if (i==(10-offset)):
      break
      
    offset+=1
  return offset
    



    
def createGraph(nucl):
  graph = []
  for i in xrange(len(nucl)):
    graph.append([])
    for j in xrange(len(nucl)):
      graph[i].append(compNucl(nucl[i],nucl[j]))
  
  return graph



def greedyTSP(graph, start, maxPath):
  path = 10
  visited = ['n'] * len(graph)
  nuclLeft = len(graph)
  visited[start] = 'v'
  
  seq = []
  seq.append(start)
  cur = start
  
  while path<maxPath:
    
    #if nuclLeft<=0:
    #  break
    nuclLeft-=1
    
    minval = 1000
    tempid = 0
    
    for i in xrange(len(graph)):
      
      if i!=cur and graph[cur][i]<minval: #visited[i]=='n'
	minval = graph[cur][i]
	tempid = i
    
    if (path+graph[cur][tempid]<=maxPath):
      visited[tempid] = 'n'
      path+=graph[cur][tempid]
      seq.append(tempid)
      cur = tempid
    else:
      break
  
   
  return seq

def printNucl(seq, graph, nucl, fpath):
  #try:
  #  os.remove("out.txt")
  f = open(fpath,"wt")
  temp = nucl[seq[0]][0:9]
  n = len(seq)
  for i in range(1,n):
    temp += nucl[seq[i]][9-graph[seq[i-1]][seq[i]]:9]

  f.write(temp)
  
  f.write("\n")
  x=0
  f.write(nucl[seq[0]])  
  for i in range(1,n):
    x += graph[seq[i-1]][seq[i]]
    f.write(x*" " + nucl[seq[i]])

  f.close()
  

############ START #############

if len(sys.argv)<3:
  print "usage: " + sys.argv[0] + " <input_file> <output_file> " 
  sys.exit()
  
nucl = loadInstFile(sys.argv[1])
graph = createGraph(nucl)

seq = []
for i in xrange(len(nucl)):
  seq.append(i)
  
printNucl(seq,graph,nucl,sys.argv[2])

  
#greedyTSP(graph,0, 209)
